package io.mft.commons.util;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数字工具类
 * @类型名称：NumberUtil
 * @说明：TODO
 * @创建者: 胡常建  
 * @创建时间: 2015年5月9日 下午5:13:26
 * @修改者: 胡常建  
 * @修改时间: 2015年5月9日 下午5:13:26
 */
public class NumberUtil {
    static Logger logger=LoggerFactory.getLogger(NumberUtil.class);
    public static <T extends Number> T ParseNumber(String number,
            Class<T> targetNumber) {
    	try {
            if (targetNumber.getName().equals(Integer.class.getName())) {
                String[] arr = number.split("\\.");
                number = arr[0];
            }
            Object numObject = targetNumber.getConstructor(String.class).newInstance(number.trim());
            if (numObject != null) {
                return (T) numObject;
            }
            return null;
		} catch (Exception e) {
			 logger.info("值："+number+"转换到"+targetNumber.getName()+"异常,返回默认值：null");
			return null;
		}

    }



    public static <T extends Number> T ParseNumber(String number,
            Class<T> targetNumber, T defaultValue) {
        try {
            T vT= ParseNumber(number, targetNumber);
            if (vT==null) {
            	 logger.info("值："+number+"转换到"+targetNumber.getName()+"异常,返回默认值："+defaultValue);
                return defaultValue;
            }
            return vT;
        } catch (Exception e) {
            logger.info("值："+number+"--->>>转换到"+targetNumber.getName()+"异常,返回默认值："+defaultValue);
            return defaultValue;
        }
    }

   

    

    public static int roundDown(double v)
    {
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, 0, BigDecimal.ROUND_DOWN).intValue();
    }
    
    public static int roundUp(double v)
    {
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, 0, BigDecimal.ROUND_UP).intValue();
    }
    
    public static double round(double v, int scale)
    {
        if (scale < 0)
        {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

}
